package top.mall.happy.oauth.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 */
public class MD5Util {

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'};

    static MessageDigest MD5 = null;

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
            ne.printStackTrace();
        }
    }

    /**
     * 获取md5值.
     *
     * @param str the string
     * @return md5串
     */
    public static String getStringMD5(String str) {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            MD5.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] data = MD5.digest();
            for (byte datum : data) {
                sb.append(HEX_DIGITS[(datum & 0xf0) >> 4]).append(HEX_DIGITS[datum & 0xf]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}